/**
 * Exercise 2.3 - htoi program, character to integer program.
 *
 */

#include <stdio.h>
#define MAXLINE 100

int my_getline(char line[], int maxline);
int htoi(char s[]);

int main(void) {
  char line[MAXLINE];
  int value;

  my_getline(line, MAXLINE);
  value = htoi(line);

  printf("The value of %s is %d\n", line, value);

  return 0;
}

int my_getline(char s[], int lim) {
  int c, i;

  for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
    s[i] = c;
  }

  if (c == '\n') {
    s[i] = '\0';
  }

  return i;
}

int htoi(char s[]) {
  int hexdigit, i = 0, inhex = 0, n;

  if (s[i] == '0') {
    ++i;
    if (s[i] == 'x' || s[i] == 'X') {
      ++i;
    }
  }

  n = 0;
  inhex = 1;

  for (; inhex == 1; ++i) {
    if (s[i] >= '0' && s[i] <= '9') {
      hexdigit = s[i] - '0';
    } else if (s[i] >= 'a' && s[i] <= 'f') {
      hexdigit = s[i] - 'a' + 10;
    } else if (s[i] >= 'A' && s[i] <= 'F') {
      hexdigit = s[i] - 'A' + 10;
    } else {
      inhex = 0;
    }

    if (inhex) {
      n = 16 * n + hexdigit;
    }
  }
  return n;
}
